import { defineStore } from 'pinia'

const useAudio = defineStore('useAudio', {
  state: () => {
    return {
      playList: [],
      currentPlay: ''
    }
  },
  actions: {
    initAudio() {
      this.playList = JSON.parse(localStorage.getItem('playList')) || []
      this.currentPlay = JSON.parse(localStorage.getItem('currentPlay')) || {}
    },
    setPlayList(item) {
      const index = this.playList.findIndex((i) => i.id === item.id)
      if (index === -1) {
        this.playList.unshift(item)
        localStorage.setItem('playList', JSON.stringify(this.playList))
      } else {
        this.playList.splice(index, 1)
        this.playList.unshift(item)
      }
    },
    setCurrentPlay(item) {
      this.currentPlay = item
      localStorage.setItem('currentPlay', JSON.stringify(item))
    },
    next() {
      if (this.playList.length > 0) {
        const index = this.playList.findIndex((i) => i.id === this.currentPlay.id)
        if (index === -1) {
          this.currentPlay = this.playList[0]
        } else {
          if (index === this.playList.length - 1) {
            this.currentPlay = this.playList[0]
          } else {
            this.currentPlay = this.playList[index + 1]
          }
        }
        localStorage.setItem('currentPlay', JSON.stringify(this.currentPlay))
      }
    },
    prev() {
      if (this.playList.length > 0) {
        const index = this.playList.findIndex((i) => i.id === this.currentPlay.id)
        if (index === -1) {
          this.currentPlay = this.playList[0]
        } else {
          if (index === 0) {
            this.currentPlay = this.playList[this.playList.length - 1]
          } else {
            this.currentPlay = this.playList[index - 1]
          }
        }
        localStorage.setItem('currentPlay', JSON.stringify(this.currentPlay))
      }
    }
  }
})

export default useAudio
